var menu;
var navbar;
var selected_menu;
var selected_submenu;
var selected_navbar;
var coordX =0;
var coordY;
var upload_t;
var upload_range;


add_css ("/modules/admin/css/admin.css");

window.sessionStorage.editmode = 0;
window.sessionStorage.drag = 0;


/*Window events*/
document.ondblclick=function(e) {
    
    if (window.event) e = window.event; 
    var element = e.srcElement? e.srcElement : e.target; 
    if (window.sessionStorage.username != null) {
       
        show_toolbar_edit();
        admin_edit_article();
    }
    window.sessionStorage.drag = 0;
    if ((window.sessionStorage.username != null)&&(window.sessionStorage.editmode == 1)) {
		    //alert(1);
        
        admin_edit_article();
    }
}
/*
document.onmousedown=function(e) {
	window.sessionStorage.drag = 0;
	if (window.event) e = window.event; 
	var clicked_element = e.srcElement? e.srcElement : e.target;
	var id = getElementId(clicked_element);
	//var id_data = id.split("_");
	if (id == "toolbar_drag") window.sessionStorage.drag = 1;
	//else if (id_data[0]=="editmenu") alert(id);
	
	
	//console.log (id);
	//Edit menu functions
	//alert(id);
}

document.onmouseup=function(e) {
  window.sessionStorage.drag = 0;
}
*/
document.onclick=function(e) {
	if (navigator.appName == "Microsoft Internet Explorer") { 
        coordX = event.clientX + document.body.scrollLeft;
        coordY = event.clientY + document.body.scrollTop;
		 } else  coordY = e.pageY;
	}





function initialize_toolbar () {
	 if (window.sessionStorage.username != null) {
	   		var admin_toolbar =  document.getElementById("admin_toolbar");
	 		if (window.sessionStorage.toolbarX > 0) admin_toolbar.style.left = window.sessionStorage.toolbarX + "px";
	   }
}

//window.onload = initialize_toolbar ();

window.onbeforeunload= function () {
    /*TODO: Add IE catch */
 /*   if (window.sessionStorage.editmode == 1) {
        if (navigator.appName !=  "Microsoft Internet Explorer")  {
            return "You have not saved your document yet.  If you continue, your work will not be saved.";
        }
    }*/
}



show_admin_toolbar ();



function load_form () {
	//alert(1);
	var form_content = 0;
	while (form_content ==0) form_content = getFile("/modules/admin/pages/logon.php");
    
    var login_pane = document.getElementById("login_pane");
    //alert(form_content);
    login_pane.innerHTML =  form_content;
    
}


function admin_log_on () {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var result = getFile("/modules/admin/pages/authorize.php?username=" + username + "&password="+password );
    if (result==1)  {
        window.sessionStorage.username = username;
        //show_admin_toolbar ();
        //hide_login_form ();
				window.location = window.sessionStorage.last_page;
    } else {
		   alert("Try again...");
		}
}

function hide_login_form () {
    window.location.reload ();
}

function show_admin_toolbar () {
    if (window.sessionStorage.username != null) {
        var toolbar = getFile("/modules/admin/pages/toolbar.php?operation="+ action +"&article="+ article+"&section="+section+"&area="+area+"&file="+file);
        var tooldiv = document.createElement('div');
        tooldiv.innerHTML = toolbar;
        document.getElementById("page").appendChild(tooldiv);
				add_css ("/modules/toolbar/templates/create/css/create.css");
    }
		
}

function do_login () {
 if (window.sessionStorage.username == null)  load_form ();
}

function do_admin_logout () {
    var result = getFile("/modules/admin/pages/logout.php");
    window.sessionStorage.removeItem("username");
		window.sessionStorage.editmode == 0;
    window.location.reload ();
}

function admin_create_article (article) {
  alert (article);
}

function show_toolbar_edit () {
     hide_menu_edit_area();
     window.sessionStorage.editmode = 1;
		 //console.debug(window.sessionStorage.editmode);
                 if (document.getElementById("edit_middle_bar_title") != null) document.getElementById("edit_middle_bar_title").style.visibility = "visible";   
		 if (document.getElementById("edit_info_bar")!=null) document.getElementById("edit_info_bar").style.visibility = "visible";
		 //document.getElementById(info_remove_box[0]).style.visibility = "visible";
		 if (document.getElementById("page_save_button") != null) document.getElementById("page_save_button").style.visibility = "visible";
		 
		 //document.getElementById("send_for_review_button").style.visibility = "visible";
		 
		 var send_for_review_button = document.getElementById("send_for_review_button");
		 if (send_for_review_button != null) send_for_review_button.style.visibility = "visible";
		 
		 var publish_save_button = document.getElementById("publish_save_button");
		 if (publish_save_button != null) publish_save_button.style.visibility = "visible";
		 
		 show_edit_elements ();
		 window.sessionStorage.removeItem("edit_menu");
		
}

function show_edit_elements () {
    if (document.getElementById("edit_info_bar") != null) document.getElementById("edit_info_bar").style.visibility="visible";
    if (document.getElementById("edit_info_bar")!= null) {
        var edit_info_bar_boxes = document.getElementById("edit_info_bar").getElementsByTagName("div");
        for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.visibility = "visible";
    }
    
}		 



function admin_edit_article () {
    document.getElementById("content_text").contentEditable='true';
		document.getElementById("content_text").style.border="dashed #0099FF 1px";
		document.getElementById("edit_content_area").style.visibility="visible";
		 var edit_info_bar_boxes = document.getElementById("edit_content_area").getElementsByTagName("div");
		 for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.visibility = "visible";
    //show_toolbar_edit ();
		 //document.getElementById("edit_content_area").style.visibility="visible"; 
    //document.getElementById("save_article").style.display = "block"; 
		
}


function  reset_elements () {
  document.getElementById("toolbar_edit").style.display = "none"; 
  document.getElementById("section_header").contentEditable='false';
  document.getElementById("save_section").style.display="none";  
  document.getElementById("save_article").style.display="none";    
  document.getElementById("save_navmenu").style.display="none"; 
  document.getElementById("toolbar_instructions").innerHTML = "Double click on element to edit it";
  return true;
}

    
function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
            }
    else return;
  return  txt;
}



function admin_disable_links () {
    objLinks = document.getElementsByTagName("a");
    for(i=0;i<objLinks.length;i++){
        objLinks[i].href = "javascript:return false;";
    }
    var admin_disable_links = document.getElementById("admin_disable_links");
    var admin_enable_links = document.getElementById("admin_enable_links");
    admin_disable_links.style.display = "none";
    admin_enable_links.style.display = "block";
    window.sessionStorage.editmode = 1; 
    return true;
}

function admin_enable_links () {
    location.reload(true);
}




var navmenu_items = new Array();
function admin_edit_navmenu () {
   var navmenu = document.getElementById("navmenu");
    navmenu.contentEditable='true'; 
    var url = section;
     /*2011-03-30 Create array containing existing contents of menu */
    navmenu_items =  get_navmenu_array ();
    document.getElementById("save_navmenu").style.display="block";
}

function get_navmenu_array () {
    var navmenu_array = new Array();
    var navmenu = document.getElementById("navmenu");
    var l = navmenu.getElementsByTagName("a");
    for (lc=0;lc<l.length;lc++) {
        var s = l[lc].getElementsByTagName("span");
        navmenu_array[lc] = s[0].innerHTML;
    }
    return navmenu_array;
}


function admin_element (element) {
		debug = 0;
    var id = getElementId(element);
		if (debug==1) console.log(id);
    //var id_split = id.split("_");
    //var content_text = id_split[0];
    //alert(window.sessionStorage.section);

    //var admin_message = document.getElementById("admin_message");
    
    //admin_message.innerHTML = section;
    //reset_elements ();
    //if (content_text=="content_text") admin_edit_article ();
		if (id=="content_text") admin_edit_article ();
    //else if (section == "navmenu") admin_edit_navmenu ();
    //else if (section == "section") admin_edit_section ();
      
    
}

function admin_edit_section () {
    var section_header = document.getElementById("section_header");
    var h =  section_header.getElementsByTagName("h3");
    h[0].contentEditable='true';
    var d =  section_header.getElementsByTagName("div");
    d[0].contentEditable='true';
    show_toolbar_edit ();
    document.getElementById("save_section").style.display="block";
    //document.designMode =  "on";
    //var section_header = document.getElementById("admin_toolbar");
    //section_header.designMode =  "off";
    //var h =  section_header.getElementsByTagName("h3");
    //h[0].contenteditable = "true";
    //alert(h[0].contenteditable);
    //for (i=0;i<h.length;i++) h[i].contenteditable = "true";
}

/*Save button functionality */

function save_page () {
 admin_save_article ();
 //window.location.reload ();
}

function publish_page () {
  var result = getFile("/modules/admin/pages/publish.php?article=" + article);
  var result2 = getFile("/modules/info_bar/publish.php?area="+area+"&section="+section+"&file="+file);
	//window.location.reload ();
  alert ("article published");
  _admin.trash_admin_buttons();
}

function send_page_for_review () {
    result= getFile("/modules/admin/pages/send_review.php?article= " + article);
				 //alert(result);
}

admin = function () {
    this.article_admin_buttons = function () {
        if (! this.admin_buttons_exists()) {
            var html = "<div id=article_admin_buttons>"
                     + "<button id=publish_save_button onclick=\"Javascript:publish_page ();\">Publish</button>"
		     + "<button id=send_for_review_button onclick=\"Javascript:send_page_for_review();\">Send for review</button>"
                     + "</div>";
            $("#edit_top_bar").append(html);
            $("#publish_save_button,#send_for_review_button").css("visibility","visible");
        }
    };
    this.admin_buttons_exists = function () {
        if (document.getElementById("article_admin_buttons") == null) return false;
        else return true;
    };
    this.trash_admin_buttons = function () {
        if (this.admin_buttons_exists) $("#article_admin_buttons").remove();
    }
    
}

_admin = new admin ();

function admin_save_article () {
    
    $.ajax({
        async: true,
        type: 'POST',
        url: "/modules/admin/pages/save.php",
        data: {
            article : article,
            html :  document.getElementById("content_text").innerHTML
        },
        success: function (result) {
            alert("article saved");
            //_admin.article_admin_buttons();
            //$("#publish_save_button,#send_for_review_button").css ({"visibility":"visible"});
        }
    });
   
    /*var content = document.getElementById("content_text");
    
		var content_text = content.innerHTML;
		var myJSONText = encodeURIComponent(content_text);
		
	  var result1 = getFile("/modules/admin/pages/save.php?article=" + article  + "&html=" + myJSONText);
    */
   
   
}



function admin_save_section() {
    var section_header = document.getElementById("section_header").innerHTML;
    var result = getFile("/modules/admin/pages/save_section.php?section=" + document.URL  + "&html=" + section_header);
    if (result == section_header) {
        window.sessionStorage.editmode = 0;
        admin_enable_links ();
    }    
}

/*2011-03-30 Save navbar */
var new_navmenu_items = new Array();
function admin_save_navmenu() {
    /*Get new item list*/
    new_navmenu_items =  get_navmenu_array ();
    
    /*Compare contents
    Must take account of all new items and changes in existing ones
    */
    var update_required =  false;
    if (new_navmenu_items.length == navmenu_items.length) {
        for (i=0;i<navmenu_items.length;i++) {
            if (navmenu_items[i] != new_navmenu_items[i]) update_required += "item " + i + "changed ";
        }
    } else update_required += navmenu_items.length + "=>" + new_navmenu_items.length;
    
    /*Do update if required*/
    if (update_required) {
        alert(update_required);
    }
}


function admin_save_info_settings (area, section, file, checked,entry) {
				 if (entry != 0) {
    		 		var params = "?area="+area+"&section="+section+"&file="+file+"&checked="+checked+"&entry="+entry;
    				var url = "/modules/admin/pages/save_info_settings.php";
						//console.log (url + params);
    				var result = getFile(url + params);
						//console.log(result);
    				window.location.reload ();
				}
}

function admin_save_info_settings2 (area, section, file, entry)
{
 var params = "?area="+area+"&section="+section+"&file="+file+"&checked=true&entry="+entry;
 alert(params);
}

//Format pages

function create_link () {
    //if (getSelText()=="") alert("Please select some text");
    //else {
        var url = prompt ("Enter URL", "http://");
        document.execCommand('createlink',false,url);
    //}
}
function remove_link () {
    //if (getSelText()=="") alert("Please select some text");
    //else {
        //var url = prompt ("Enter URL", "http://");
        document.execCommand('unlink',false,null);
    //}
}

function insert_image () {
    var url = prompt ("Enter image location", "/images/");
    document.execCommand('insertimage',false,url);
    
}

function justify_text (justify) {
				 document.body.contentEditable = true;
				 document.execCommand(justify, false, null);
				 document.body.contentEditable = false;
}

function json_from_file (file) {
	//var json;
	//var json= eval("(" + getFile(file) + ")");
	var json = JSON.parse(getFile(file));
	return json;
}

function json_count (json_data) {
	var objCount = 0;
	for(_obj in json_data) objCount++;
	return objCount;
}

menu = json_from_file("/modules/menu/menu_json.php?text=true");	
	navbar = json_from_file("/modules/menu/navbar_json.php?text=true");

function show_menu_edit () {
	var menu_data;
	hide_toolbar_edit ();
	hide_edit_article ();
	show_menu_edit_area ();
	
	load_menu_data ();
	//if (area != "") load_sub_menu_data(area);
	//if (section != "") load_navbar_data(section);
	window.sessionStorage.edit_menu = true;
        $(document).ready(function (){$("#publish_menus_area").show();})
        
}

function isEmpty(obj) { 
	if (JSON.stringify(menu) == "[]") return true;
	else return false;
}

function load_menu_data () {
	selected_menu = "";
	selected_submenu = "";
	selected_navbar = "";
	var menu_data = document.getElementById("menu_data");
	var text = "";
	var menu_count = 0;
	var last_menu = "";
	
	if ((menu != null) && (! isEmpty(menu))) {
	for (_menu in menu) {
		menu_count++;
		last_menu = _menu;
		text += "<div style=display:none id=\"new_menu_" + _menu + "\" ><fieldset>";
		text += "<legend>New Menu</legend>";
		text += "<label for=\"new_menu_" + _menu + "_text\">Text:&nbsp;</label><input id=\"new_menu_" + _menu + "_text\"><br>";
		text += "<label for=\"new_menu_" + _menu + "_url\">Url:&nbsp;&nbsp;&nbsp;</label><input id=\"new_menu_" + _menu + "_url\"><br>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/accept.png\" onclick=\"add_new_menu_before('" + _menu + "')\" title=\"add new navmenu\" >";
		text += "</fieldset></div>";
		
		text += "<fieldset id=\"" + _menu + "\" onclick=\"load_sub_menu_data (this.id);load_navbar_data(this.id);\" >";
		text += "<legend>" + _menu;
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/add.png\" onclick=\"show_newmenu_div('" + _menu + "')\"  >";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/delete.png\" onclick=\"delete_menu('" + _menu + "')\" >";		
	
		text +=	"</legend>";
		
		
		
		text += "<input id=\"" + _menu + "_text\" value=\"" + menu[_menu].text + "\" onkeyup=\"update_menu_data(this.id)\"  >";
		var url = "";
		if (menu[_menu].url != undefined) url = menu[_menu].url;
		text += "<input id=\"" + _menu + "_url\" value=\"" + url + "\" onkeyup=\"update_menu_data(this.id)\" >";
		text += "</fieldset>";	
	}
	}
	//text += menu_count;
	if (menu_count > 0) {
		text += "<fieldset >";
		text += "<legend>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/add.png\" onclick=\"show_newmenu_div('" + menu_count + "')\"  >";
		text += "</legend>";
		
		
		text += "<div style=display:none id=\"new_menu_" + menu_count + "\" ><fieldset>";
		text += "<label for=\"new_menu_" + menu_count + "_text\">Text:&nbsp;</label><input id=\"new_menu_" + menu_count + "_text\"><br>";
		text += "<label for=\"new_menu_" + menu_count + "_url\">Url:&nbsp;&nbsp;&nbsp;</label><input id=\"new_menu_" + menu_count + "_url\"><br>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/accept.png\" onclick=\"add_new_menu_after('" + menu_count + "','" + last_menu + "')\" title=\"add new navmenu\" >";
		text += "</fieldset></div>";
		
		
		text += "</fieldset>";
	} else {
		text += "<fieldset  >";
		text += "<legend>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/add.png\" onclick=\"show_newmenu_div('" + menu_count + "')\"  >";
		text += "</legend>";
		
		
		text += "<div style=display:none id=\"new_menu_" + menu_count + "\" ><fieldset>";
		text += "<label for=\"new_menu_" + menu_count + "_text\">Text:&nbsp;</label><input id=\"new_menu_" + menu_count + "_text\"><br>";
		text += "<label for=\"new_menu_" + menu_count + "_url\">Url:&nbsp;&nbsp;&nbsp;</label><input id=\"new_menu_" + menu_count + "_url\"><br>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/accept.png\" onclick=\"add_new_menu()\" title=\"add new navmenu\" >";
		text += "</fieldset></div>";
		
		
		text += "</fieldset>";
		
	}
	
	menu_data.innerHTML = text;
}

function update_menu_data(id) {
	var ip = document.getElementById(id);
	var element_type = id.replace(selected_menu+"_","");
	menu[selected_menu][element_type] = ip.value;
	//document.getElementById("menu_save_area").style.visibility = "visible";
	
}

function load_sub_menu_data (id) {
	   selected_menu = id;
	   selected_submenu = "";
	   selected_navbar = "";
	   var sub_menu_data = document.getElementById("sub_menu_data");
	   sub_menu_data.style.display = "block";
	   var text = id;
	   text = id;
	   
	   var menu_count = 0;
	   if  ((menu[id] != undefined) && (menu[id]["items"] != undefined)) {
	   for (_menu in menu[id]["items"]) {
		   if (menu[id]["items"][_menu].text != undefined) {
			   var menu_id = menu[id]["items"][_menu].section;
			   text += "<fieldset id=\"" + menu_id + "\" onclick=\"load_navbar_data (this.id)\"  >";
			   text += "<legend>" + menu[id]["items"][_menu].section ;
			   text += "<img src=\"/modules/toolbar/templates/create/images/icons/delete.png\" onclick=\"delete_sub_menu('" + menu_id + "')\" >";
			   
			   text += "</legend>";
			   text += "<input id=\"" + menu_count + "_text\" value=\"" + menu[id]["items"][_menu].text + "\" onkeyup=\"update_sub_menu_data(this.id)\" >";
			   var url = "";
			   if (menu[id]["items"][_menu].url != undefined) url = menu[id]["items"][_menu].url;
			   text += "<input id=\"" + menu_count + "_url\" value=\"" + url + "\" onkeyup=\"update_sub_menu_data(this.id)\" >";
			   text += "</fieldset>";
			   text += "<img src=\"/modules/toolbar/templates/create/images/icons/add.png\" onclick=\"insert_sub_menu('" + menu_id + "')\"  >";
			   text += "<div id=\"" + menu_id + "_insert_after\" >";
			   
			   text += "<label for=\"" + menu_id + "_new_text\" style=display:none>Text</label>";
			   text += "<input id=\"" + menu_id + "_new_text\" style=display:none>";
			   text += "<label for=\"" + menu_id + "_new_url\" style=display:none>URL</label>";
			   text += "<input id=\"" + menu_id + "_new_url\" style=display:none>";
			   text += "<img style=\"display:none\" ";
			   text += " onclick=\"insert_sub_menu_element('" + menu_id + "')\" ";
			   text += " src=\"/modules/toolbar/templates/create/images/icons/accept.png\" onclick=\"insert_sub_menu_element('" + menu_id + "')\"  >";
			   text += "</div>";
			   menu_count++;
	   		}
	   }
	   }
	   if (menu_count == 0) {
		   
		   text += "<img src=\"/modules/toolbar/templates/create/images/icons/add.png\" onclick=\"new_sub_menu('" + id + "')\" title=\"add sub-menu\" >";
		   
		   text += "<div class=\"new_sub_menu_x\" id=\"new_sub_menu_" + id + "\" ><fieldset>";
		   text += "<label for=\"new_sub_menu_" + id + "_text\">Text:&nbsp;</label><input id=\"new_sub_menu_" + id + "_text\"><br>";
		   text += "<label for=\"new_sub_menu_" + id + "_url\">Url:&nbsp;&nbsp;&nbsp;</label><input id=\"new_sub_menu_" + id + "_url\"><br>";
		   text += "<img src=\"/modules/toolbar/templates/create/images/icons/accept.png\" onclick=\"add_new_sub_menu('" + id + "')\" title=\"add new sub_menu\" >";
		  
		   text += "</fieldset></div>";
	   }
		   
		   
	   //sub_menu_data.innerHTML = getFile("/modules/admin/pages/sub_menu_details.php?menu_name=" + id);
	   sub_menu_data.style.visibility = "visible";
	   //var edit_info_bar_boxes =  sub_menu_data.getElementsByTagName("div");
	   //for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.visibility = "visible";
	   sub_menu_data.scrollTop = 0;   
	   var navmenu_data = document.getElementById("navmenu_data");
	   navmenu_data.innerHTML = "";
	   
	   sub_menu_data.innerHTML = text;
	   
	   $(".new_sub_menu_x").click (function () {alert($(this).attr("id"))})
}

function update_sub_menu_data (id) {
	var ip = document.getElementById(id);
	var element_type = id.split("_");
	
	menu[selected_menu]["items"][element_type[0]][element_type[1]] = ip.value;	
	//document.getElementById("menu_save_area").style.visibility = "visible";
}


function load_navbar_data (id) {
	selected_submenu = id;
	selected_navbar = "";
	var navmenu_data = document.getElementById("navmenu_data");
	//navmenu_data.innerHTML = getFile("/modules/admin/pages/navmenu_details.php?sub_menu_name=" + id);
	
	text = id;
	var nav_count = 0;
	for (_navbar in navbar[id]) {
		if ((navbar[id][_navbar] != null) && (navbar[id][_navbar].text != undefined)) {
		text += "<fieldset id=" + id + "aaa" + _navbar + " onclick=\"toolbar.load_subnav(this.id);\">";
		text += "<legend>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/add.png\" onclick=\"show_navmenu_div('" + _navbar + "')\"  >";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/delete.png\" onclick=\"delete_navmenu('" + _navbar + "')\" >";
		
		
		

		text += "</legend>";
		
		text += "<div style=display:none id=\"new_navmenu_" + _navbar + "\" ><fieldset>";
		text += "<label for=\"new_navmenu_" + _navbar + "_text\">Text:&nbsp;</label><input id=\"new_navmenu_" + _navbar + "_text\"><br>";
		text += "<label for=\"new_navmenu_" + _navbar + "_url\">Url:&nbsp;&nbsp;&nbsp;</label><input id=\"new_navmenu_" + _navbar + "_url\"><br>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/accept.png\" onclick=\"add_new_navmenu_before('" + _navbar + "')\" title=\"add new navmenu\" >";
		text += "</fieldset></div>";
		
		
		text += "<input  id=\"nav_" + nav_count + "_text\" value=\"" +  navbar[id][_navbar].text + "\"  onkeyup=\"update_navbar_data(this.id)\">";
		var url = "";
		if (navbar[id][_navbar].url != undefined) url = navbar[id][_navbar].url;
		text += "<input id=\"nav_" + nav_count + "_url\" value=\"" + url + "\" onkeyup=\"update_navbar_data(this.id)\">";
		text += "</fieldset>";
		nav_count++;
		}
	}
	if (nav_count > 0) {
		text += "<fieldset>";
		text += "<legend>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/add.png\" onclick=\"show_navmenu_div('" + nav_count + "')\"  >";
		text += "</legend>";
		
		
		text += "<div style=display:none id=\"new_navmenu_" + nav_count + "\" ><fieldset>";
		text += "<label for=\"new_navmenu_" + nav_count + "_text\">Text:&nbsp;</label><input id=\"new_navmenu_" + nav_count + "_text\"><br>";
		text += "<label for=\"new_navmenu_" + nav_count + "_url\">Url:&nbsp;&nbsp;&nbsp;</label><input id=\"new_navmenu_" + nav_count + "_url\"><br>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/accept.png\" onclick=\"add_new_navmenu_after('" + nav_count + "')\" title=\"add new navmenu\" >";
		text += "</fieldset></div>";
		
		
		text += "</fieldset>";
	}
	if (nav_count == 0) {
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/add.png\" onclick=\"new_navmenu('" + id + "')\" title=\"add navmenu\" >";
		   
		text += "<div id=\"new_navmenu_" + id + "\" ><fieldset>";
		text += "<label for=\"new_navmenu_" + id + "_text\">Text:&nbsp;</label><input id=\"new_sub_menu_" + id + "_text\"><br>";
		text += "<label for=\"new_navmenu_" + id + "_url\">Url:&nbsp;&nbsp;&nbsp;</label><input id=\"new_sub_menu_" + id + "_url\"><br>";
		text += "<img src=\"/modules/toolbar/templates/create/images/icons/accept.png\" onclick=\"add_new_navmenu('" + id + "')\" title=\"add new navmenu\" >";
		text += "</fieldset></div>";
	}
	
	navmenu_data.innerHTML = text;
	navmenu_data.style.visibility = "visible";
	//var edit_info_bar_boxes =  navmenu_data.getElementsByTagName("div");
	//for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.visibility = "visible";
	navmenu_data.scrollTop = 0;   	
	
}

function update_navbar_data (id) {
	var ip = document.getElementById(id);
	id = id.replace("nav_", "");
	var element_id = id.replace("_text", "");
	element_id = element_id.replace("_url", "");
	var element_type = id.replace(element_id + "_", "");
    //console.log (element_id + " " + element_type);
	//console.log(selected_submenu + " " + navbar[selected_submenu][element_type[0]][element_type[1]] + " " + ip.value);
	
	//console.log(navbar[selected_submenu][element_id][element_type] + " => " + ip.value);
	navbar[selected_submenu][element_id][element_type] = ip.value;	
	//document.getElementById("menu_save_area").style.visibility = "visible";
}

function save_menu_changes () {
	
        
	
	var json_menu =  base64_encode (JSON.stringify(menu));
	
	
	var navbar_text = JSON.stringify(navbar);
	
	var json_navbar = base64_encode (navbar_text);
	
	
	var params = "json_menu=" + json_menu + "&json_navbar=" + json_navbar;
	var result = postFile("/modules/admin/pages/json_save_menu.php", params);
	
	if (result == "saved") {
            var update = confirm("The menu has been updated\n\nDo you want to refresh the page to see the changes?")
            if (update) {window.location.reload()}
        }
	else alert(result);
    
    
   
   
       
	
}

function show_menu_edit_area () {
				 document.getElementById("edit_menu_bar").style.visibility = "visible";
				 if (document.getElementById("edit_menu_bar") != null) var edit_info_bar_boxes = document.getElementById("edit_menu_bar").getElementsByTagName("div");
				 for (i=0;i<edit_info_bar_boxes.length;i++) {
					 edit_info_bar_boxes[i].style.visibility = "visible";
					 edit_info_bar_boxes[i].style.display = "block";
				 }
				 
				 var menu_status = getFile("/modules/admin/pages/menu_status.php");
				 //document.getElementById("menu_publish_area").style.display = "block";
}

function hide_menu_edit_area () {
				 if (document.getElementById("edit_menu_bar") != null) document.getElementById("edit_menu_bar").style.visibility = "hidden";
				 if (document.getElementById("edit_menu_bar") != null) {
                                     var edit_info_bar_boxes = document.getElementById("edit_menu_bar").getElementsByTagName("div");
				 for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.visibility = "hidden";
                                 
                                 
                                 }
				 
				 if (document.getElementById("sub_menu_data") != null) document.getElementById("sub_menu_data").style.visibility = "hidden";
				 if (document.getElementById("navmenu_data") != null) document.getElementById("navmenu_data").style.visibility = "hidden";
				 if (document.getElementById("menu_save_area") != null) document.getElementById("menu_save_area").style.visibility = "hidden";
				 if (document.getElementById("menu_publish_area")!= null) document.getElementById("menu_publish_area").style.display = "none";
}


function hide_toolbar_edit () {
     window.sessionStorage.editmode = 1;
		 //console.debug(window.sessionStorage.editmode);
     document.getElementById("edit_middle_bar_title").style.visibility = "hidden";   
		 document.getElementById("edit_info_bar").style.visibility = "hidden";
		 //document.getElementById(info_remove_box[0]).style.visibility = "visible";
		 //document.getElementById("page_save_button").style.visibility = "hidden";
		 
		 //document.getElementById("send_for_review_button").style.visibility = "visible";
		 
		 var send_for_review_button = document.getElementById("send_for_review_button");
		 if (send_for_review_button != null) send_for_review_button.style.visibility = "hidden";
		 
		 var publish_save_button = document.getElementById("publish_save_button");
		 if (publish_save_button != null) publish_save_button.style.visibility = "hidden";
		 
		 document.getElementById("edit_info_bar").style.visibility="visible";
		 var edit_info_bar_boxes = document.getElementById("edit_info_bar").getElementsByTagName("div");
		 for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.visibility = "hidden";
		 
		 
}

function hide_edit_article () {
    var content_text = document.getElementById("content_text");
		if (content_text != null) {
    document.getElementById("content_text").contentEditable='false';
		document.getElementById("content_text").style.border="0px";
		}
		document.getElementById("edit_content_area").style.visibility="hidden";
		 var edit_info_bar_boxes = document.getElementById("edit_content_area").getElementsByTagName("div");
		 for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.visibility = "hidden";
    //show_toolbar_edit ();
		 //document.getElementById("edit_content_area").style.visibility="visible"; 
    //document.getElementById("save_article").style.display = "block"; 
		
}


function show_sub_menu_edit (id) {
   var sub_menu_data = document.getElementById("sub_menu_data");
   sub_menu_data.innerHTML = getFile("/modules/admin/pages/sub_menu_details.php?menu_name=" + id);
   sub_menu_data.style.visibility = "visible";
   var edit_info_bar_boxes =  sub_menu_data.getElementsByTagName("div");
   for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.visibility = "visible";
   sub_menu_data.scrollTop = 0;   
   var navmenu_data = document.getElementById("navmenu_data");
   navmenu_data.innerHTML = "";
}


function show_navmenu_edit(id) {
	var navmenu_data = document.getElementById("navmenu_data");
	navmenu_data.innerHTML = getFile("/modules/admin/pages/navmenu_details.php?sub_menu_name=" + id);
	navmenu_data.style.visibility = "visible";
	var edit_info_bar_boxes =  navmenu_data.getElementsByTagName("div");
	for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.visibility = "visible";
	navmenu_data.scrollTop = 0;   
}

function initialize_menu_save(id) {
	var menu_save_area = document.getElementById("menu_save_area");
	menu_save_area.style.visibility = "visible";
}

function mouseX(evt) {
	if (evt.pageX) return evt.pageX;
	else if (evt.clientX)
	   return evt.clientX + (document.documentElement.scrollLeft ?
	   document.documentElement.scrollLeft :
	   document.body.scrollLeft);
	else return null;
	}

function insert_sub_menu(id) {
	var insert_after = document.getElementById(id + "_insert_after");
	insert_after.style.visibility = "visible";
	var edit_info_bar_boxes =  insert_after.getElementsByTagName("input");
	for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.display = "block";
	var edit_info_bar_boxes =  insert_after.getElementsByTagName("img");
	for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.display = "block";
	var edit_info_bar_boxes =  insert_after.getElementsByTagName("label");
	for (i=0;i<edit_info_bar_boxes.length;i++) edit_info_bar_boxes[i].style.display = "block";
	//console.log (JSON.stringify(menu[selected_menu].items));
	//console.log(e.clientX);
	//console.log(insert_after.top);
	//console.log (JSON.stringify(menu));
}

function insert_sub_menu_element(id) {
	var current_menu = JSON.stringify(menu);
	
	for (_menu in menu[selected_menu].items) {
		if (id == menu[selected_menu].items[_menu].section) {
			var item_string = "{\"text\":\"" + menu[selected_menu].items[_menu].text + "\",\"section\":\"" + menu[selected_menu].items[_menu].section + "\",\"url\":\"" + menu[selected_menu].items[_menu].url + "\"}";
			var new_text = document.getElementById(id + "_new_text").value;
			//var new_section = newSectionId();
			var new_section = textToId (new_text);
			var new_url = document.getElementById(id + "_new_url").value;
		    var new_item_string = "{\"text\":\"" + new_text + "\",\"section\":\"" + new_section + "\",\"url\":\"" + new_url + "\"}";
		    var new_menu = current_menu.replace(item_string, item_string + "," + new_item_string);
		    //console.log(new_item_string);
		    menu = JSON.parse (new_menu);
		    
		    save_menu_changes ();
		   
		}
	}
}

function delete_sub_menu(id) {
	var current_menu = JSON.stringify(menu);
	for (_menu in menu[selected_menu].items) {
		if (id == menu[selected_menu].items[_menu].section) {
			//delete menu[selected_menu].items[_menu];
			var item_string = "{\"text\":\"" + menu[selected_menu].items[_menu].text + "\",\"section\":\"" + menu[selected_menu].items[_menu].section + "\",\"url\":\"" + menu[selected_menu].items[_menu].url + "\"}";
		    var new_menu = current_menu.replace(item_string, "");
		    new_menu = new_menu.replace(",,", ",");
		    new_menu = new_menu.replace("},]", "}]");
		    new_menu = new_menu.replace("[,{", "[{");
		    //console.log (new_menu);
		    menu = JSON.parse (new_menu);
		    save_menu_changes ();
		}
	}
	//var current_menu = JSON.stringify(menu);
	//console.log(current_menu);
}
 function new_sub_menu(id) {
	 
	 var new_sub_menu_details = document.getElementById("new_sub_menu_" + id);
	 new_sub_menu_details.style.visibility = "visible";
	
 }
 
 function new_navmenu(id) {
	 var new_sub_menu_details = document.getElementById("new_navmenu_" + id);
	 new_sub_menu_details.style.visibility = "visible";
	 
 }
 
 function add_new_sub_menu (id) {
	 //var title = document.getElementById("new_sub_menu_" + id + "_title");
	 var text = document.getElementById("new_sub_menu_" + id + "_text");
	 var url = document.getElementById("new_sub_menu_" + id + "_url");
	 if (text.value == "") alert("Please enter text for the submenu");
	 else {
		//var title = newSectionId();
		 var title = textToId (text.value);
		//console.log(id + " " + title);

		menu[id]["items"] = [];
		menu[id].items.push({text:text.value,section:title,url:url.value});
		
		save_menu_changes ();
	 }
	 var current_menu = JSON.stringify(menu);
	 //console.log(current_menu);
	 
 }
 
 function show_newmenu_div (id) {
	 new_navmenu = document.getElementById("new_menu_" + id);
	 new_navmenu.style.display = "block";
	 new_navmenu.style.visibility = "visible"; 
	 
 }
 
 function show_navmenu_div(id) {
	// console.log(id);
	 new_navmenu = document.getElementById("new_navmenu_" + id);
	 new_navmenu.style.display = "block";
	 new_navmenu.style.visibility = "visible";
 }
 
 function add_new_navmenu_before(id) {
	 var current_navbar = JSON.stringify(navbar); 
	 var current_data = JSON.stringify(navbar[selected_submenu][id]);
	 var new_text = document.getElementById("new_navmenu_" + id + "_text").value;
	 var new_url = document.getElementById("new_navmenu_" + id + "_url").value;
	 
	 var new_data = "{\"text\":\"" + new_text + "\",\"url\":\"" + new_url + "\"}";
	 
	 var new_navbar = current_navbar.replace(current_data, new_data + "," + current_data);
	 navbar = JSON.parse (new_navbar);
	 save_menu_changes ();
	 
 }
 
 function newSectionId () {
	 return getFile("/modules/admin/pages/new_section_id.php"); 
	 
 }
 
 function newMenuId () {
	 return getFile("/modules/admin/pages/new_menu_id.php");
 }
 
 function add_new_menu_before (id) {
	 //var new_id = document.getElementById("new_menu_" + id + "_id").value;
	 var new_text = document.getElementById("new_menu_" + id + "_text").value;
	 var new_url = document.getElementById("new_menu_" + id + "_url").value;
	 
	 if (new_text=="") {
	     alert("The text field is mandatory");
		 return false;
	 }
	 var current_menu = JSON.stringify(menu); 
	 /*
	  * {"text":"Home","url":"http://create","items":[]} -> 
	  * "home":{"text":"Home","url":"http://create","items":[]}
	  */
	 var next_menu = "\"" +id + "\":" + JSON.stringify(menu[id]); 
	 
	 
	 //var new_id = newMenuId();
	 var new_id = textToId (new_text);
	 
	 
	 if (new_url != "") var new_menu = "\"" + new_id +  "\":{\"text\":\"" + new_text + "\",\"url\":\"" + new_url + "\",\"items\":[]}";
	 else var new_menu = "\"" + new_id +  "\":{\"text\":\"" + new_text + "\",\"items\":[]}";
	 var new_full_menu = current_menu.replace(next_menu, new_menu + "," + next_menu);
	 menu = JSON.parse (new_full_menu);
	 save_menu_changes ();
	 return true;
 }
 
 function add_new_menu_after (id, last_menu) {
	 //var new_id = document.getElementById("new_menu_" + id + "_id").value;
	 var new_text = document.getElementById("new_menu_" + id + "_text").value;
	 var new_url = document.getElementById("new_menu_" + id + "_url").value;
	 
	 if (new_text=="") {
	     alert("An ID and text is required");
		 return false;
	 }
	 var current_menu = JSON.stringify(menu); 
	 /*
	  * {"text":"Home","url":"http://create","items":[]} -> 
	  * "home":{"text":"Home","url":"http://create","items":[]}
	  */
	 
	 //var new_id = newMenuId();
	 var new_id = textToId (new_text);
	 var next_menu = "\"" + last_menu + "\":" + JSON.stringify(menu[last_menu]); 
	 if (new_url != "") var new_menu = "\"" + new_id +  "\":{\"text\":\"" + new_text + "\",\"url\":\"" + new_url + "\",\"items\":[]}";
	 else var new_menu = "\"" + new_id +  "\":{\"text\":\"" + new_text + "\",\"items\":[]}";
	 
	 var new_full_menu = current_menu.replace(next_menu,  next_menu + "," + new_menu);
	 //console.log(new_full_menu);
	 menu = JSON.parse (new_full_menu);
	 save_menu_changes ();
	 
	 return true;
 }
 
 function delete_menu(id) {
	
	 var current_menu = JSON.stringify(menu);
	 var delete_menu = "\"" +id + "\":" + JSON.stringify(menu[id]);
	 
	 var new_menu = current_menu.replace(delete_menu, "");
	 new_menu = new_menu.replace(",,", ",");
	 new_menu = new_menu.replace("},]", "}]");
	 new_menu = new_menu.replace("[,{", "[{");
	 new_menu = new_menu.replace("{,", "{");
	 new_menu = new_menu.replace(",}", "}");
	 menu = JSON.parse (new_menu);
	 save_menu_changes ();
 }
 
 function add_new_navmenu_after(id) {
	 var last_id = id - 1;
	 var current_navbar = JSON.stringify(navbar); 
	 var current_data = JSON.stringify(navbar[selected_submenu][last_id]);
	 var new_text = document.getElementById("new_navmenu_" + id + "_text").value;
	 var new_url = document.getElementById("new_navmenu_" + id + "_url").value;
	 
	 var new_data = "{\"text\":\"" + new_text + "\",\"url\":\"" + new_url + "\"}";
	 
	 var new_navbar = current_navbar.replace(current_data,  current_data + "," + new_data);
	 navbar = JSON.parse (new_navbar);
	 save_menu_changes ();
	 
 } 
 
 function textToId (text) {
	 var id = text.toLowerCase();
	 id = id.replace(/ /g,"_");
	 id = id.replace(/\&/g,"and");
	 return id; 
 }
 
 function add_new_menu() {
		//var id = newMenuId();
		var text = document.getElementById("new_menu_0_text").value;
		
		var id = textToId (text);
		
	    var url = document.getElementById("new_menu_0_url").value;
	    var menu_text = "{\"" + id + "\":{\"text\":\"" + text + "\",\"url\":\"" + url + "\"}}";
	    console.log (menu_text);
	    menu = JSON.parse (menu_text);
	    save_menu_changes ();
	}
 
 function json_count (obj) {
	 var count = 0;
	 for ( o in obj ) count++;
	 return count;
 }
 
 function add_new_navmenu (id) {
	 
	 var text = document.getElementById("new_sub_menu_" + id + "_text").value;
	 var url = document.getElementById("new_sub_menu_" + id + "_url").value;
	 console.log(id);
	 if (! navbar ) navbar = {};
	 
	 var i = json_count(navbar[id]);
	 if (i ==0) navbar[id] = {};
	 navbar[id][i]= {text:text,section:id,url:url};
	 //navbar[id][i+1]= {text:text,section:id,url:url};
	 
	 
	 //alert 
	 //navbar[id].push({text:text,section:id,url:url});
	 //navbar[id].text = text;
	 //navbar[id].url = url;
	 
	 //navbar[id].push({text:text,section:id,url:url});
	 //navbar[].push ({text:text,section:id,url:url});
	 //console.log(JSON.stringify(navbar));
	 //{"text":"Transport","url":"Transport.html"}
	 //navbar[id].push()
	 //navbar[].push(id);
	 //navbar[id].push("{text:text,section:id,url:url}");
	 save_menu_changes ();
 }
 
 //function cleanNav (n)
 
 function delete_navmenu(id) {
	 var current_navbar = JSON.stringify(navbar); 
	 //var item_string = "{\"text\":\"" + navbar[selected_submenu][id].text + "\",\"url\":\"" + navbar[selected_submenu][id].url + "\"}";
	 //var new_navbar = current_navbar.replace(item_string, "");
	 //new_navbar = new_navbar.replace(",,", ",");
	 //new_navbar = new_navbar.replace("},]", "}]");
	 //new_navbar = new_navbar.replace("[,{", "[{");
	 //navbar = JSON.parse (new_navbar);
	 //console.log(new_navbar);
	 
	 console.log(selected_submenu)
	 delete navbar[selected_submenu][id];
	 var new_navbar = JSON.stringify(navbar);
	 //new_navbar = new_navbar.replace("null,","");
	 //new_navbar = new_navbar.replace(",null","");
	 //new_navbar = new_navbar.replace(",null","");
	 
	 console.log(new_navbar);
	 navbar = JSON.parse(new_navbar);
	 
	 //console.log(JSON.stringify(JSON.parse(JSON.stringify(navbar))));
	 save_menu_changes (); 
 }
 
 
function publish_menus () {
	result = getFile("/modules/admin/pages/publish_menus.php");
	alert(result);
	//window.location.reload();
}


//Gallery functions
function load_gallery_images () {
	var image_gallery = document.getElementById("image_gallery_content");
	image_gallery.innerHTML = getFile("/modules/gallery/index.php?folder=/images");
	
}

function close_gallery() {
	var image_gallery = document.getElementById("image_gallery");
	image_gallery.className = "image_gallery_unloaded";
	image_gallery = document.getElementById("image_upload_area");
	image_gallery.className = "image_gallery_unloaded";
}

function show_gallery() {
	load_gallery_images ();
	
	var image_gallery = document.getElementById("image_gallery");
	image_gallery.className = "image_gallery_loaded";
	var image_upload_area = document.getElementById("image_upload_area");
	image_upload_area.className = "image_gallery_unloaded";
	
}



function insert_article_image(id) {
	
	show_gallery ();
	//var imgSrc = prompt('Enter image location', '');

	//if(imgSrc != null)
	//iView.document.execCommand('insertimage', false, imgSrc); 
}

function check_upload_completed () {
	
	var image_upload_area = document.getElementById("image_upload_area");
	if (image_upload_area.className == "image_gallery_loaded") upload_t =  setTimeout ( "check_upload_completed ()", 100 );
	else {
		var uploaded_image_file = getFile("/modules/uploader/uploaded_image_file.php");
		if (range) range.execCommand('insertimage', false, "/images/" + uploaded_image_file);
		else document.execCommand('insertimage', false, "/images/" + uploaded_image_file); 
	}
	
}


function  upload_article_image(id) {
	if ( document.selection ) range = document.selection.createRange();
	else range = false;
	setAjaxParameter("uploaded_image_file" , "");
	var image_upload_area = document.getElementById("image_upload_area");
	image_upload_area.className = "image_gallery_loaded";
	var image_gallery = document.getElementById("image_gallery");
	image_gallery.className = "image_gallery_unloaded";
	check_upload_completed ();
}


function insert_gallery_image(src) {
	document.execCommand('insertimage', false, src);
}





 if (window.sessionStorage.edit_menu != undefined) show_menu_edit();

 
